﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Utilities;
using System.Data;
using Billing.Controls;
using System.Configuration;
using System.Drawing.Printing;
using Billing.Dtos;

namespace Billing.Windows
{
    public partial class VendorBillingGrid : Window
    {
        public int VendorID { get; set; }
        public string Vendor { get; set; }
        public string BillNo { get; set; }
        public double TotalAmount { get; set; }

        public VendorBillingGrid(string company, int companyID)
        {
            InitializeComponent();
            VendorID = companyID;
            Vendor = company;

            header.Text = "Vendor - " + Vendor;
            lbBillingGrid.Items.Add(new VendorBillingGridItemControl(VendorID));
            lbBillingGrid.Focus();
            lbBillingGrid.SelectedIndex = 0;
            UpdateBillItemsSlNo();
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            UpdateBillItemsSlNo();
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }

        void UpdateBillItemsSlNo()
        {
            try
            {
                int SlNo = 1;
                foreach (VendorBillingGridItemControl itemControl in lbBillingGrid.Items)
                {
                    itemControl.lblSrNo.Content = SlNo++;
                }
            }
            catch (Exception) { }
        }

        VendorBillingGridItemControl GetSelectedItem()
        {
            try
            {
                return lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void lbBillingGrid_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter && GetSelectedItem().txtQty.IsFocused)
                {
                    VendorBillingGridItemControl item = (lbBillingGrid.SelectedItem as VendorBillingGridItemControl);
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    else
                    {
                        if (item.txtPrice.Tag != null)
                            item.txtPrice.Text = (value * double.Parse(item.txtPrice.Tag.ToString())).ToString();
                    }

                    if (!(SetSelectedIndexForEmptyItem()))
                    {
                        lbBillingGrid.Items.Add(new VendorBillingGridItemControl(VendorID));
                        SetLastSelectedItem();
                    }
                }
                else if (e.Key == Key.Up)
                {
                    VendorBillingGridItemControl item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    else
                    {
                        if (item.txtPrice.Tag != null)
                            item.txtPrice.Text = (value * double.Parse(item.txtPrice.Tag.ToString())).ToString();
                    }

                    lbBillingGrid.SelectedIndex = lbBillingGrid.SelectedIndex > 0 ? lbBillingGrid.SelectedIndex - 1 : 0;
                    item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Down)
                {
                    VendorBillingGridItemControl item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    else
                    {
                        if (item.txtPrice.Tag != null)
                            item.txtPrice.Text = (value * double.Parse(item.txtPrice.Tag.ToString())).ToString();
                    }


                    lbBillingGrid.SelectedIndex = lbBillingGrid.SelectedIndex > -1 ? lbBillingGrid.SelectedIndex + 1 : 0;
                    item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Left)
                {
                    VendorBillingGridItemControl item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtCode.Focus();
                        item.txtCode.SelectAll();
                    }
                }
                else if (e.Key == Key.Right)
                {
                    VendorBillingGridItemControl item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Delete)
                {
                    VendorBillingGridItemControl item = lbBillingGrid.SelectedItem as VendorBillingGridItemControl;
                    item.txtCode.Clear();
                    item.txtDesc.Clear();
                    item.txtQty.Clear();
                    item.txtCode.Focus();
                }
                else if (e.Key == Key.F1)
                {
                    SetTotalAmount();

                    new Confirm().ShowDialog();

                    bool isItemsRemoved = false;
                    for (int i = 0; i < lbBillingGrid.Items.Count; i++)
                    {
                        VendorBillingGridItemControl item = lbBillingGrid.Items[i] as VendorBillingGridItemControl;
                        if (item.txtQty.Text == "0" || item.txtQty.Text == string.Empty || item.txtCode.Text == string.Empty)
                        {
                            lbBillingGrid.Items.Remove(lbBillingGrid.Items[i]);
                            isItemsRemoved = true;
                            i -= 1;
                        }
                    }
                    if (isItemsRemoved)
                        UpdateBillItemsSlNo();

                    VendorDto vendor = new VendorDto();
                    vendor.VendorID = VendorID;
                    vendor.Vendor = Vendor;
                    vendor.NetTotalAmount = decimal.Parse(lblFinalPrice.Content.ToString());

                    this.BillNo = Database.GenerateBillForVendor(lbBillingGrid.Items, double.Parse(lblFinalPrice.Content.ToString()), vendor);
                    
                    this.TotalAmount = double.Parse(lblFinalPrice.Content.ToString());

                    if (PrintCommon.PrintItems != null)
                        PrintCommon.PrintItems.Clear();
                    if (PrintCommon.CreditNoteItems != null)
                        PrintCommon.CreditNoteItems.Clear();
                    if (PrintCommon.BulkOrderItems != null)
                        PrintCommon.BulkOrderItems.Clear();
                    if (PrintCommon.VendorItems != null)
                        PrintCommon.VendorItems.Clear();

                    foreach (VendorBillingGridItemControl item in lbBillingGrid.Items)
                    {
                        PrintCommon.VendorItems.Add(item);
                    }

                    Storage.DiscountByPercentage = string.Empty;
                    PrintCommon.Discount = 0;
                    PrintCommon.TotalAmt = TotalAmount;
                    Storage.IsFirstBill = false;
                    Storage.CreditNoteCompany = Vendor;
                    Storage.BillNo = BillNo;

                    if (ConfigurationManager.AppSettings["PrinterType"] != null && ConfigurationManager.AppSettings["PrinterType"].ToString() == "new")
                    {
                        NewPrinter form = new NewPrinter();
                        form.printDocument1.PrintController = new StandardPrintController();
                        form.printDocument1.Print();
                    }
                    else
                    {   
                        Form1 form = new Form1();
                        form.printDocument1.PrintController = new StandardPrintController();
                        form.printDocument1.Print();
                    }

                    if (this.BillNo == string.Empty)
                    {
                        MessageBox.Show("Some Exception Has Occurred. Please try again later.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    else
                    {
                        //MessageBox.Show("Bill Generated Successfully.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                        return;
                    }
                }

                SetTotalAmount();
            }
            catch (Exception) { }
        }

        private void SetLastSelectedItem()
        {
            try
            {
                lbBillingGrid.SelectedIndex = lbBillingGrid.Items.Count - 1;
            }
            catch (Exception) { }
        }

        private bool SetSelectedIndexForEmptyItem()
        {
            foreach (VendorBillingGridItemControl item in lbBillingGrid.Items)
            {
                if (item.txtCode.Text.ToString() == string.Empty || item.txtQty.Text.ToString() == string.Empty)
                {
                    lbBillingGrid.SelectedItem = item;
                    (lbBillingGrid.SelectedItem as VendorBillingGridItemControl).txtCode.Focus();
                    return true;
                }
            }
            return false;
        }

        private void SetTotalAmount()
        {
            double value = 0;
            foreach (VendorBillingGridItemControl item in lbBillingGrid.Items)
            {
                if (item.txtPrice.Text != string.Empty)
                    value += double.Parse(item.txtPrice.Text);
            }

            lblFinalPrice.Content = value.ToString();
        }
    }
}
